#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/8/8 9:19
# @File    : thread_is_alive.py
# @Software: PyCharm
"""
python3.9 has _native_id(threadID)
python3.5 just has _ident
"""

import time
import threading
from datetime import datetime


class Mytest(object):
    def __init__(self):
        self.process_list = []
        self.start_time = time.time()

    def heartbeat(self):
        if time.time() - self.start_time > 10:
            exit(0)

        print(datetime.now())
        print(threading.enumerate().__str__(), len(self.process_list))
        print("-" * 30)
        for run_process in self.process_list:
            print(run_process)
        print("-" * 30)

        for run_process in self.process_list:
            print("run_process: ", run_process.__dict__, run_process.name)
            if not run_process.isAlive() and run_process.name not in threading.enumerate().__str__():
                print("{} is not alived".format(run_process))
                self.process_list.remove(run_process)

        if 'mytask' not in threading.enumerate().__str__():
            mytask = MyTask()
            self.process_list.append(mytask)
            print("mytask not start,then start it")
            mytask.start()

        hb = threading.Timer(5, self.heartbeat)
        hb.start()


class MyTask(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.name = "mytask"

    def run(self) -> None:
        print("MyTask.isAlive()", self.isAlive())
        if "_native_id" in self.__dict__.keys():
            print("threadID is: {}".format(self.__dict__.get('_native_id')))
        time.sleep(2)

    def isAlive(self) -> bool:
        if self._is_stopped:
            return False
        else:
            return True


if __name__ == '__main__':
    mm = Mytest()
    mm.heartbeat()


